package com.itheima.reggie.contreller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private UserService userService;

    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders) {
        //登录用户的id
        Long userid = BaseContext.getCurrentId();
        //获取地址
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        //获取购物车
        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ShoppingCart::getUserId, userid);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lqw);
        if (shoppingCartList==null||shoppingCartList.size()<=0){
            throw  new CustomException("购物车为空");
        }

        //获取用户信息
        User user = userService.getById(userid);
        if (user==null){
            throw new CustomException("用户不存在");
        }

        //生成订单号
        long id = IdWorker.getId();

        //总金额
        AtomicInteger atomicInteger = new AtomicInteger(0);

        List<OrderDetail> orderDetailList = new ArrayList<>();

        //设置订单详情表
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail detail = new OrderDetail();
            detail.setName(shoppingCart.getName());
            detail.setOrderId(id);
            detail.setDishId(shoppingCart.getDishId());
            detail.setDishId(shoppingCart.getDishId());
            detail.setSetmealId(shoppingCart.getSetmealId());
            detail.setDishFlavor(shoppingCart.getDishFlavor());
            detail.setNumber(shoppingCart.getNumber());
            detail.setImage(shoppingCart.getImage());
            detail.setAmount(shoppingCart.getAmount());
            atomicInteger.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            orderDetailList.add(detail);
        }


        //设置订单表
        orders.setId(id);
        //订单状态
        orders.setStatus(1);
        //添加订单号
        orders.setNumber(String.valueOf(id));
        //添加用户
        orders.setUserId(userid);
        //下单时间
        orders.setOrderTime(LocalDateTime.now());
        //记账时间
        orders.setCheckoutTime(LocalDateTime.now());
        //设置实收金额
        orders.setAmount(new BigDecimal(atomicInteger.get()));
        //设置用户
        orders.setUserName(user.getName());
        //设置手机号
        orders.setPhone(user.getPhone());
        //设置收货地址
        orders.setAddress(
                (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName()) +
                        (addressBook.getCityName() == null ? "" : addressBook.getCityName()) +
                        (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName()) +
                        (addressBook.getDetail() == null ? "" : addressBook.getDetail())
        );
        //设置收货人
        orders.setConsignee(addressBook.getConsignee());
        ordersService.save(orders);
        orderDetailService.saveBatch(orderDetailList);
        shoppingCartService.remove(lqw);
        return R.success("下单成功");
    }


    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String number,String beginTime,String endTime) {
        //构建分页构造器
        Page<Orders> ordersPage = new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(number != null, Orders::getNumber, number);
        queryWrapper.ge(StringUtils.isNotEmpty(beginTime), Orders::getOrderTime,beginTime);
        queryWrapper.le(StringUtils.isNotEmpty(endTime), Orders::getOrderTime,endTime);
        queryWrapper.orderByDesc(Orders::getOrderTime);

        ordersService.page(ordersPage, queryWrapper);
        return R.success(ordersPage);
    }
    // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    @GetMapping("/userPage")
    public R<Page> userpage(int page,int pageSize){
        //构造器
        Page<Orders> ordersPage = new Page<>(page,pageSize);
        Page<OrderDetail> orderDetailPage = new Page<>();

        //查询订单表
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,BaseContext.getCurrentId());
        queryWrapper.orderByDesc(Orders::getOrderTime);
        ordersService.page(ordersPage,queryWrapper);
        return R.success(ordersPage);


    /*
        ArrayList<OrderDetail> orderDetails = new ArrayList<>();
        LambdaQueryWrapper<OrderDetail> lwq = new LambdaQueryWrapper<>();
        //对象拷贝
        BeanUtils.copyProperties(ordersPage,orderDetailPage,"records");
        List<Orders> records = ordersPage.getRecords();
        for (Orders record : records) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(record,orderDetail);
            lwq.eq(OrderDetail::getOrderId,record.getId());
            OrderDetail one = orderDetailService.getOne(lwq);
            if (one==null){
                throw new CustomException("订单详情不存在");
            }
          //  orderDetail.setNumber(one.getNumber());
            orderDetails.add(orderDetail);
        }
        orderDetailPage.setRecords(orderDetails);

        return R.success(orderDetailPage);*/
    }
}
